package Java7_Concurrency_Cookbook.concurrent_custom.custom_runnable_scheduled_future;

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * <b>定制运行在定时线程池中的任务</b><br/>
 * <br/>
 * 执行器(ThreadPoolExecutor, ScheduledThreadPoolExecutor)并不直接执行任务(Runnable, Callable)<br/>
 * 执行器通过线程(Thread)去执行任务.<br/>
 * ThreadPoolExecutor中通过ThreadFactory创建的Thread去执行任务.<br/>
 * ScheduledThreadPoolExecutor中通过RunnableScheduledFuture来执行定时任务<br/>
 * <br/>
 * ScheduledThreadPoolExecutor能执行两类任务: 延迟任务, 周期性任务.<br/>
 * 示例中, 我们自定义的MyScheduledTask(RunnableScheduledFuture)也提供了对这两种任务的支持.<br/>
 *
 * 想要实现自定义定时任务, 必须实现自定义的定时执行器. <br/>
 * 为了在定时执行器中使用MyScheduledTask, 我们必须覆盖decorateTask()方法. <br/>
 * 覆盖这个方法将缺省定时任务替换为MyScheduledTask任务<br/>
 * <br/>
 *
 * @author lixiangke
 * @date 2017/11/24
 */
public class Main {
    public static void main(String[] args) throws InterruptedException {
        MyScheduledThreadPoolExecutor executor = new MyScheduledThreadPoolExecutor(2);
        Task task = new Task();
        System.out.printf("Main: %s\n", new Date());
        executor.schedule(task, 1, TimeUnit.SECONDS);
        TimeUnit.SECONDS.sleep(3);

        task = new Task();
        System.out.printf("Main: %s\n", new Date());
        executor.scheduleAtFixedRate(task, 1, 3, TimeUnit.SECONDS);
        TimeUnit.SECONDS.sleep(10);

        executor.shutdown();
        executor.awaitTermination(1, TimeUnit.DAYS);
        System.out.printf("Main: End of the program.");
    }
}
